package jzqb.controller;

import haha.life.common.RandomStringUtils;
import haha.life.common.SysTool;
import haha.life.normal.FileuploadUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:
 *
 * @author BaiGe
 * @date: 2021/5/12 10:02
 * @Version 1.0
 */
@Api(tags = "富文本编辑器")
@RestController
@CrossOrigin(allowCredentials = "true")
@RequestMapping("/ueditor")
public class UeditorController {


    //富文本图片存放路径
    @Value("${filePath.UEditorImagePath}")
    private String UEditorImagePath;
    //富文本图片存放路径
    @Value("${filePath.UEditorFilePath}")
    private String UEditorFilePath;
    //本机IP
    @Value("${filePath.localUrl}")
    private String localUrl;


    /**
     * 上传配置：即不走config.json，模拟config.json里的内容，解决后端配置项不正确，无法上传的问题
     *
     * @return
     */
    @RequestMapping("/config")
    public void uploadConfig(HttpServletResponse response) {
        String s = "UE_Config_Json_LKJHGFDSA = {\n" +
                "               \"basePath\":\"D:/cnki/JZQBDataBase/JZQBProjectData/UEditor\", \n" +
                "               \"imageActionName\": \"ueditorUploadImage\",\n" +
                "                \"imageFieldName\": \"upfile\", \n" +
                "                \"imageMaxSize\": 2048000, \n" +
                "                \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\", \".tiff\", \".jfif\"], \n" +
                "                \"imageCompressEnable\": true, \n" +
                "                \"imageCompressBorder\": 1600, \n" +
                "                \"imageInsertAlign\": \"none\", \n" +
                "                \"imageUrlPrefix\": \"\",\n" +
//                "                \"imageUrlPrefix\": \" "+localUrl+"/ueditor/echoImage/\",\n" +
                "                \"imagePathFormat\": \"{filename}\",\n" +
                "                \"fileActionName\": \"ueditorUploadFile\", \n" +
                "                \"fileFieldName\": \"upfile\", \n" +
                "                \"filePathFormat\": \"{filename}\",\n" +
                "                \"fileUrlPrefix\": \"\", \n" +
//              "                \"fileUrlPrefix\": \""+localUrl+"/ueditor/echoFile/\", \n" +
                "                \"fileMaxSize\": 51200000, \n" +
                "                \"fileAllowFiles\": [ \".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"," +
                "                                      \".flv\", \".swf\", \".mkv\", \".avi\", \".rm\", \".rmvb\", \".mpeg\", \".mpg\"," +
                "                                      \".ogg\", \".ogv\", \".mov\", \".wmv\", \".mp4\", \".webm\", \".mp3\", \".wav\", \".mid\"," +
                "                                      \".rar\", \".zip\", \".tar\", \".gz\", \".7z\", \".bz2\", \".cab\", \".iso\"," +
                "                                       \".doc\", \".docx\", \".xls\",\".xlsx\", \".ppt\", \".pptx\", \".pdf\", \".txt\", \".md\", \".xml\"]\n" +

                "}";
        // return s;
        response.setHeader("Content-Type", "text/javascript");
        try {
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/config")
    public ModelAndView forward(MultipartFile upfile, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView();
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Type", "text/html");
        String value = request.getParameter("action");
        switch (value) {
            case "ueditorUploadImage":
                mv.setViewName("forward:/ueditor/ueditorUploadImage");
                break;
            case "ueditorUploadFile":
                mv.setViewName("forward:/ueditor/ueditorUploadFile");
                break;
        }
        return mv;
    }


    @ApiOperation(value = "富文本上传图片")
    @RequestMapping(value = "/ueditorUploadImage", method = RequestMethod.POST)
    public Map<String, String> ueditorUploadImage(@RequestParam(value = "upfile") MultipartFile upfile, HttpServletRequest request) {
        //true 不跨域 ,false 跨域
        boolean isLocal = this.validate(request);
        Map<String, String> map = new HashMap<>();
        //当前时间
        String nowTime = new SimpleDateFormat(SysTool.dateFormat_date).format(new Date());
        //原文件名
        String fileName = upfile.getOriginalFilename();
        //文件存放前的随机目录
        String randomFilePath = RandomStringUtils.getRandomString(7);
        //目录  日期加随机数  如:2021-05-25/abcde
        String basePath = nowTime + "\\" + randomFilePath;
        //文件存放的完整路径
        String filePath = new File(UEditorImagePath, basePath).toString();
        //时间毫秒数
        String milli = String.valueOf(System.currentTimeMillis());
        //加了时间毫秒数的文件名
        String realFileName = milli + "_" + fileName;
        //文件对象
//        File uploadedFile = new File(filePath, fileName);
        File uploadedFile = new File(filePath, realFileName);
        //图片存放绝对路径
        String absolutePath = uploadedFile.toString();
        //图片回显路径
        String echoUrl = nowTime + "/" + randomFilePath + "/" + realFileName;
        try {
            //创建目录
            File targetFile = new File(filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            //保存文件
            upfile.transferTo(uploadedFile);//上传
            if (isLocal) {//本地(不跨域)  使用相对路径
                map.put("url", "/ueditor/echoImage" + "/" + echoUrl + "\"  onerror=\"javascript:getImage(this,'ueditor/echoImage','" + echoUrl + "')");
            } else {//非本地(跨域)  使用绝对路径
                map.put("url", localUrl + "/ueditor/echoImage" + "/" + echoUrl + "\"  onerror=\"javascript:getImage(this,'ueditor/echoImage','" + echoUrl + "')");
            }
//          map.put("url", "javascript:getImage('ueditor/echoImage',"+"'"+echoUrl+"')\" onerror=\"javascript:getImage(this,'ueditor/echoImage',\'"+echoUrl+"');");
            map.put("state", "SUCCESS");
            map.put("original", "");
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    @ApiOperation(value = "图片回显")
    @GetMapping("/echoImage/{date}/{path}/{name}")
    public byte[] echoImage(@PathVariable("date") String date, @PathVariable("path") String path, @PathVariable("name") String name) {
        String allPath = UEditorImagePath + "\\" + date + "\\" + path + "\\" + name;
        byte[] imageBinary = FileuploadUtils.getImageBinary(allPath);
        return imageBinary;
    }

    @ApiOperation(value = "富文本上传附件")
    @RequestMapping(value = "/ueditorUploadFile", method = RequestMethod.POST)
    public Map<String, String> ueditorUploadFile(@RequestParam(value = "upfile") MultipartFile upfile) {
        Map<String, String> map = new HashMap<>();
        //当前时间
        String nowTime = new SimpleDateFormat(SysTool.dateFormat_date).format(new Date());
        //原文件名
        String originalFilename = upfile.getOriginalFilename();
        //文件存放前的随机目录
        String randomFilePath = RandomStringUtils.getRandomString(7);
        //目录  日期加随机数  如:2021-05-25/abcde
        String basePath = nowTime + "\\" + randomFilePath;
        //文件存放完整路径
        String filePath = new File(UEditorFilePath, basePath).toString();
        //加了时间毫秒数的文件名
        String realFileName = System.currentTimeMillis() + "_" + originalFilename;
        //图片回显路径
        String echoUrl = nowTime + "/" + randomFilePath + "/" + realFileName;
        try {
            /*upfile:文件;filePath:目录;fileName:文件名*/
            File targetFile = new File(filePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            //保存文件
            upfile.transferTo(new File(filePath, realFileName));

            map.put("url", echoUrl);
            map.put("url", "javascript:getFile('ueditor/echoFile'," + "'" + echoUrl + "')");
            map.put("state", "SUCCESS");
            map.put("original", originalFilename);
            map.put("title", originalFilename);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @ApiOperation(value = "附件下载")
    @GetMapping("/echoFile/{date}/{path}/{name}")
    public String echoFile(@PathVariable("date") String date, @PathVariable("path") String path, @PathVariable("name") String name,
                           HttpServletResponse response) {
        String allPath = UEditorFilePath + "\\" + date + "\\" + path + "\\" + name;
        try {
            //清空一下response对象，否则出现缓存什么的
            response.reset();
            //指明这是一个下载的respond
            response.setContentType("application/x-download");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            //<span style="font-family: Arial, Helvetica, sans-serif;">原文件名若为中文，需要转码</span>
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(name.split("_")[1], "UTF-8"));
            ServletOutputStream sos = response.getOutputStream();
            BufferedInputStream fin = new BufferedInputStream(new FileInputStream(allPath));
            byte[] content = new byte[1024];
            int length;
            while ((length = fin.read(content, 0, content.length)) != -1) {
                sos.write(content, 0, length);
            }
            fin.close();
            sos.flush();
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation(value = "判断是否跨域")
    public boolean validate(HttpServletRequest request) {
        String host = request.getHeader("host");
        String referer = request.getHeader("referer");
        boolean isCors=referer.contains(host);
        return isCors; //true 不跨域  false跨域
    }

//    @ApiOperation(value = "判断是否跨域")
//    public boolean validate(HttpServletRequest request) {
//        String Referer = "";
//        boolean referer_sign = true; // true 站内提交，不跨域 //false 站外提交，跨域
//        Enumeration headerValues = request.getHeaders("Referer");
//        while (headerValues.hasMoreElements())
//            Referer = (String) headerValues.nextElement();
//        // 判断是否存在请求页面
//        if (Referer == null || Referer.length() < 1)
//            referer_sign = false;
//        else {
//            // 判断请求页面和getRequestURI是否相同
//            String servername_str = request.getServerName();
//            if (servername_str != null || servername_str.length() > 0) {
//                int index = 0;
//                if (Referer.indexOf("https://") == 0) {
//                    index = 8;
//                } else if (Referer.indexOf("http://") == 0) {
//                    index = 7;
//                }
//                if (Referer.length() - index < servername_str.length()) // 长度不够
//                    referer_sign = false;
//                else { // 比较字符串（主机名称）是否相同
//                    String referer_str = Referer.substring(index, index + servername_str.length());
//                    if (!servername_str.equalsIgnoreCase(referer_str))
//                        referer_sign = false;
//                }
//            } else
//                referer_sign = false;
//        }
//        return referer_sign;
//    }



}
